package com.xhdx.java8;

import java.util.Optional;

/**
 * 测试Optional
 * 
 */
public class OptionalTest {
    public static void main(String args[]){
        OptionalTest test = new OptionalTest();
        try{
            test.test1();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        try{
            test.test2(); 
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        test.test3();
        test.test4();
    }
    //of
    public void test1() {
        Optional<People> op = Optional.of(new People());
        //正常输出
        System.out.println(op.get()); 
        Optional<People> op1 = Optional.of(null);
        //空指针异常
        System.out.println(op1.get());
    }
    //empty
    public void test2() {
        Optional<People> op = Optional.empty();
        //java.util.NoSuchElementException
        //不会出现空指针异常
        System.out.println(op.get());
    }
    //ofNullable orElse orElseGet
    public void test3() {
        Optional<People> op = Optional.ofNullable(new People());
        //如果有元素，不是空或null
        if(op.isPresent()) {
            System.out.println(op.get());
        }
        People emp = op.orElse(new People("张三"));
        System.out.println(emp);
        //与orElse区别在于他接收一个函数式接口，可以写自己逻辑，比如if true
        //返回A对象，else 返回B对象
        People emp2 = op.orElseGet(() -> new People());
        System.out.println(emp2);
    }
    //map flatMap
    public void test4(){
        Optional<People> op = Optional.of(new People(101, "王五", 18, 9999.99));
        
        Optional<String> op2 = op.map(People :: getName);
        System.out.println(op2.get());
        
        Optional<String> op3 = op.flatMap((e) -> Optional.of(e.getName()));
        System.out.println(op3.get());
    }
}
